<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\Packet;
use App\Support\Config;
use App\Support\Currency;
use Moontoast\Math\BigNumber;
use Illuminate\Bus\Queueable;
use App\Models\ConfigUserLevel;
use Illuminate\Support\Facades\DB;
use App\Models\ConfigDynamicRelease;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class DynamicRelease implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $value;

    public function __construct(User $user, $value)
    {
        $this->user = $user;
        if ($value instanceof BigNumber) {
            $value = (string) $value;
        }
        $this->value = $value;
    }

    /**
     * @throws \App\Exceptions\ConfigNotSetException
     */
    public function handle()
    {	
      \Log::info('DynamicRelease');
        $levels = ConfigUserLevel::get()->keyBy('scale')->toArray();
        $configs = ConfigDynamicRelease::get()->keyBy('scale_id')->toArray();
        $i = 1;
        $user = $this->user;
        do {
            if (!$user->parent) {
                break;
            }
            $user = $user->parent;
            $level = $levels[$user->level];
            $config = $configs[$user->level];
            if ($i > $level['computational_algebra']) {
                break;
            }
            if ($i == 1) {
                $ratio = $config['dynamic_direct_rule'];
            } else {
                $ratio = $config['dynamic_indirect_rule'];
            }

            $value = big_number($this->value)
                ->multiply($ratio)->divide('100');

            $value = (string) $value;
            if ($value <= 0) {
                continue;
            }

            $packet = Packet::create([
                'value' => $value,
                'user_id' => $user->id,
                'type' => Packet::TYPE_TEAM,
                'expired_at' => now()->addHour(24)->toDateTimeString(),
                'currency' => (Config::getVrtsReprint() == 0) ? Currency::VRT : Currency::VRTS
            ]);

            if (Config::getVrtsReprint() == 1) {
                if ($value > $user->vrt) {
                    $value = $user->vrt;
                }
                $user->decrement('vrt', $value);
                DB::table('records')->insert([
                    'type' => '动态释放',
                    'user_id' => $user->id,
                    'currency' => Currency::VRT,
                    'recordable_id' => $packet->id,
                    'value' => (string) $value->negate(),
                    'recordable_type' => 'App\Models\Packet'
                ]);
            }

            $i = $i + 1;
        } while ($user->parent_id);
    }
}
